package com.lcn.core.db;

import com.lcn.comm.domain.TxTransactionLocal;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * <p>类说明</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @create: 2017-12-25 10:56
 */
public class LCNDataSourceProxy extends AbstractDataSource<Connection> {

    /**
     * 创建LCN代理连接池
     *
     * @param connection
     * @param txTransactionLocal
     * @return
     */
    protected Connection createLcnConnection(Connection connection, TxTransactionLocal txTransactionLocal) {
        nowCount++;
        LCNConnectionProxy lcnConnectionProxy = new LCNConnectionProxy(connection, dataSourceService, subNowCount);
        pools.put(txTransactionLocal.getGroupId(), lcnConnectionProxy);
        txTransactionLocal.setHasConnection(true);
        return lcnConnectionProxy;
    }

    /**
     * 获取数据库连接对象
     *
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        return getConnection(null, null);
    }

    /**
     * 获取数据库连接对象
     *
     * @param username
     * @param password
     * @return
     * @throws SQLException
     */
    public Connection getConnection(String username, String password) throws SQLException {
        Connection connection = (Connection) loadConnection();
        if (connection == null) {
            if (StringUtils.isNotEmpty(username))
                connection = initLCNConnection(getDataSource().getConnection(username, password));
            else
                connection = initLCNConnection(getDataSource().getConnection());
            if (connection == null) {
                throw new SQLException("连接池已用完");
            }
        }
        return connection;
    }

    /**
     * 是否是同一个事务下
     *
     * @param groupId 事务组id
     * @return true是，false否
     */
    public boolean hasGroup(String groupId) {
        return pools.containsKey(groupId);
    }

    /**
     * 是否是 事务操作
     *
     * @return true是，false否
     */
    public boolean hasTransaction() {
        return true;
    }
}
